package com.zhump.springcloud.netflix.consums.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 本地测试负载均衡
 */
@RestController
@RequestMapping("/ribbon")
public class ExtRibbonControoler {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    private AtomicInteger count = new AtomicInteger();
    @RequestMapping("/consums")
    private String Consums(){
        List<ServiceInstance> instances = discoveryClient.getInstances("spring-cloud-netflix-eureka-provide");
        if (instances == null || instances.size() <=0){
            return "没有在集群环境中获取服务地址";
        }
        //集群接口总数
        int instancesSize = instances.size();
        //接口总次数
        int andAdd = count.getAndAdd(1);
        //取模
        int i = andAdd % instancesSize;
        //获取请求地址
        String string = instances.get(i).getUri().toString();
        String resut = restTemplate.getForObject(string + "/provide/hello", String.class);
        System.out.println("返回接口请求地址"+string);
        return resut;
    }
}
